<template>
  <div class="contain-edit">
    <div class="header">
      <p>房东管理/编辑房东</p>
      <el-button class="link" type="primary">
        <router-link to="/landlordList" style="color: #fff;">返回</router-link>
      </el-button>
    </div>
    <div class="main">
      <el-form :model="information" :rules="rules" ref="information" label-width="120px" class="">
        <el-form-item label="房东：" prop="name">
          <el-input v-model="information.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select v-model="information.sex" placeholder="请选择">
            <el-option
              v-for="item in sexList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <el-input v-model="information.mobile" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="information.password" placeholder="请输入 "></el-input>
        </el-form-item>
        <el-form-item label="身份证号：" prop="idCardNo">
          <el-input v-model="information.idCardNo" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="身份证正面：" prop="idcardkey1">
          <el-upload  list-type="picture-card"
                      :action="upLoadUrl"
                      :class="{uploadShow: fileShowList && fileShowList.length>=1 ? true : false}"
                      :file-list='fileShowList'
                      :on-remove="handleRemove"
                      :before-upload="beforePicsUpload"
                      :limit="1">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('information')"  :loading="loading">保存</el-button>
          <el-button @click="$router.push('/landlordList')">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
  let CONSTANT = require('../../constant/constant.js');
  let common = require("../../common.js");
  import $ from 'jquery'
  import $axios from 'axios'
  export default {
    data() {
      var validateCode =  (rule, value, callback) => {
        var reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
        if (!reg.test(value)){ return callback(new Error('身份证号格式有误')); }
        return callback();
      };
      return {
        id:null,
        upLoadUrl: "",
        information:{
          name: "",
          sex: "",
          mobile: "",
          password: '',
          idCardNo: "",
          idcardkey1: ""
        },
        sexList: [{
          label: "男性",
          value: "male"
        },{
          label: "女性",
          value: "female"
        },{
          label: "中性",
          value: "unknow"
        }],
        rules: {
          name: [
            { required: true, message: '请输入房东', trigger: 'blur' },
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入电话号码', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          'idCardNo': [
            {required: true, message: '请输入身份证号', trigger: 'blur'},
            {  validator: validateCode, trigger: 'blur' }
          ],
          'idcardkey1': [
            {required: true, message: '请上传租客身份证', trigger: 'blur'}
          ],
        },
        loading: false,
        fileShowList: [],
        imagesList: []
      };
    },
    components:{
      'bg-editor':()=>import('../common/bg-editor.vue')
    },
    mounted() {
      this.id  = this.$router.currentRoute.query.id;
      if(this.id){
        this.getDetail();
      }
    },
    methods: {
      getDetail(){
        let url = CONSTANT.URL.MESSAGE.DETAIL;
        let data = {
          id:this.id
        } ;
        common.requestAjax(url,{},data,(res)=>{
          this.information = res.data.bussData
        })
      },
      beforePicsUpload(file) {
        let url =CONSTANT.URL.COMMON.UPLOAD;
        let param = {
          suffix:file.name.split(".")[1],   // 文件后缀  png
          contentType:file.type             // 文件类型  image/png
        }
        common.requestAjax(url,param,null,(res)=> {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.imagesList.push(res.data.bussData.fileKey)

          let downloadUrl = res.data.bussData.downloadUrl;
          common.uploadFile(this.upLoadUrl,file,file.type,(res)=>{
            this.fileShowList.push({
              url:downloadUrl
            })
          })
        });
      },
      handleRemove(file, fileList) {
        let arr = []
        let deleteUrl = file.url;
        let list = this.fileShowList;
        list.forEach((item,index)=>{
          if(item.url == deleteUrl){
            list.splice(index,1);
          }
        })
        fileList.map( (item, index) => {
          arr.push(item.url.split("com/")[1])
        })
        this.imagesList = arr
      },
      submitForm(formName) {
        this.information.idcardkey1 = this.imagesList[0];
          this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true;
            if(this.id){
              var url = CONSTANT.URL.LANDLORD.UPDATE;
            }else{
              var url = CONSTANT.URL.LANDLORD.ADD;
            }
            let data = {
              name:this.information.name,
              mobile: this.information.mobile,
              sex: this.information.sex,
              password: this.information.password,
              idCardNo: this.information.idCardNo,
              idcardkey1: this.information.idcardkey1,
              id: this.id ? this.id : ''
            };
            let param = JSON.stringify(data);
            common.requestAjax(url, param, null, res => {
              if(res.status == 200) {
                this.$message({
                  type: 'success',
                  message: '保存成功!'
                });
                this.loading = false;
                this.$router.push("/landlordList");
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
                this.loading = false;
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },


    }
  }
</script>

<style lang="scss" scoped >
  @import '/static/bootstrap.css';
  @import '/sys/static/bootstrap.css';
  .el-form-item__content{
    margin-left: 0;
  }
  .avatar-uploader {
    border-radius: 6px;
    box-sizing: border-box;
    vertical-align: top;
    .el-upload {
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
        border: 1px dashed #d9d9d9 !important;
        border-radius: 6px;
        margin-left: 6px;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
    .el-upload:hover {
      border-color: #20a0ff;
    }
  }
</style>
